<?php
namespace app\admin\validate;

/**
 * 验证器
 */
use think\Validate;

class Partition extends Validate
{
    protected $rule = [
        'name'        => 'require|max:25|unique:partition',
        'platform_id' => 'require',
        'http'        => 'url',
        'num'         => 'require|number|checknum:type',
        'gameport'    => 'number',
        'userport'    => 'number',
        'logport'     => 'number',
    ];

    protected $message = [
        'name.require'        => '名称必填',
        'name.max'            => '名称最多不能超过25个字符',
        'name.unique'         => '名称存在',
        'platform_id.require' => '渠道必须存在',
        'num.require'         => '分区编号不能为空',
        'num.checknum'        => '当前分区下此分区编号已经存在',
    ];

    // 自定义验证规则
    protected function checknum($value, $rule, $data = [])
    {
        if (empty($data['id'])) {

            if (\Db::name('partition')->where([['num', '=', $data['num']], ['platform_id', '=', $data['platform_id']]])->count() > 0) {
                return false; //当前
            } else {
                return true;
            }
        } else {
            if ((\Db::name('partition')->where([['num', '=', $data['num']]])->count() > 0)) {
                if ((\Db::name('partition')->where([['num', '=', $data['num']], ['platform_id', '=', $data['platform_id']], ['id', '=', $data['id']]])->count() > 0)) {
                    return true; //当前
                } else {
                    return false;
                }
            } else {
                return true;
            }

        }
    }
}
